package mission_tour.solution;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class tour_quizevent extends Activity implements ServerIp{
    /** Called when the activity is first created. */
	ArrayList<quizs> quiz_list;
	int sec = 20;
	private TimerTask second;
	AlertDialog.Builder nologin;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tour_quizevent);
        
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);	//	화면 안꺼짐
        
        final ProgressDialog nowloding = ProgressDialog.show(tour_quizevent.this,"","퀴즈를 불러오고 있습니다....",true);
        
        ImageView time_bar = (ImageView) findViewById(R.id.quiz_time_bar);
        Animation time_an = AnimationUtils.loadAnimation(this, R.anim.time);
        time_bar.startAnimation(time_an);
        
        second = new TimerTask() {
			public void run() {
				sec--;
				if(sec == -1 ){
					second.cancel();
					if(items.quiz_user_selected == items.quiz_answer){	
						if((items.quiz_no+1) == quiz_list.size()){//퀴즈 모든문제 풀이 완료
							Intent intent = new Intent(tour_quizevent.this, quiz_answer_ok.class);
							startActivityForResult(intent, 0);
							finish();
						}else{	//퀴즈 문제가 남았을 경우
							runOnUiThread(new Runnable(){
					            @Override
					             public void run() {
					            	Toast.makeText(tour_quizevent.this,"정답입니다! 다음문제로 이동합니다",Toast.LENGTH_SHORT).show();
					             }
					        });
							
							items.quiz_no = items.quiz_no+1;
							Intent intent = new Intent(tour_quizevent.this, tour_quizevent.class);
							startActivityForResult(intent, 0);
							finish();
						}
						
					}else{	//틀렸을 경우
						Intent intent = new Intent(tour_quizevent.this, quiz_failure.class);
						startActivityForResult(intent, 0);
						finish();
					}
				}
			}
		};
		Timer timer = new Timer();
		timer.schedule(second, 0, 1000);
		
		final Button answer1 = (Button) findViewById(R.id.answer1);
		final Button answer2 = (Button) findViewById(R.id.answer2);
		final Button answer3 = (Button) findViewById(R.id.answer3);
		final Button answer4 = (Button) findViewById(R.id.answer4);
		final Button quiz_ok_btn = (Button) findViewById(R.id.quiz_ok_btn);
        
        final ImageView answer1_check = (ImageView) findViewById(R.id.answer1_check);
        final ImageView answer2_check = (ImageView) findViewById(R.id.answer2_check);
        final ImageView answer3_check = (ImageView) findViewById(R.id.answer3_check);
        final ImageView answer4_check = (ImageView) findViewById(R.id.answer4_check);

        final TextView quiz_subject_text = (TextView) findViewById(R.id.quiz_subject_text);
        final TextView quiz_content_text = (TextView) findViewById(R.id.quiz_content_text);
    	
		quiz_list = new ArrayList<quizs>();
		
		new Thread(new Runnable() {    
			@Override
			public void run() {
				URL url = null;
		        String resultString =null;
		        try {
		        	
		        	url = new URL(tour_quiz_call+"?tour_position="+items.map_position+"&app_type="+items.apptype+"&q_type=2");
				
			        HttpURLConnection http = (HttpURLConnection)url.openConnection();  
			
					BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));
					StringBuffer buffer = new StringBuffer();
					 
					int c;  
					 
					while((c=in.read()) != -1){
						buffer.append((char)c);
					}
					
					resultString= buffer.toString().trim();
					
		        } catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					runOnUiThread(new Runnable(){
			            @Override
			             public void run() {
			            	nologin = new AlertDialog.Builder(tour_quizevent.this);
			    			nologin.setTitle(items.appname);
			    			nologin.setMessage("서버에 접속이 되지 않습니다\n네트워크를 확인 후 다시 시도해 주세요");
			    			nologin.setIcon(R.drawable.icon);
			    			nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
			    				@Override
			    				public void onClick(DialogInterface dialog, int which) {
			    					// TODO Auto-generated method stub
			    					moveTaskToBack(true);
			    					android.os.Process.killProcess(android.os.Process.myPid());
			    				}
			    			});
			    			nologin.show();
			             }
			        });
					e.printStackTrace();
				}
				try {
		            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		            factory.setNamespaceAware(true);
		            
		            boolean tagok = false;
		            
		            String[] quiz_call = null;
		            
		            XmlPullParser xpp = factory.newPullParser();
		            xpp.setInput(new StringReader(resultString));
		            
		            int eventType = xpp.getEventType();
		            
		            while (eventType != XmlPullParser.END_DOCUMENT) {
		                
		            	if(eventType == XmlPullParser.START_DOCUMENT) {
		                    System.out.println("Start document");
		                }
		            	
		            	if (eventType == XmlPullParser.END_DOCUMENT) {
		                    System.out.println("End document");
		                }
		            	
		            	if (eventType == XmlPullParser.START_TAG) {
		            		
		            		if(xpp.getName().equals("name")){
		            			tagok = true;
		            		}
		                }
		            	
		            	if (eventType == XmlPullParser.END_TAG) {
		                }
		            	
		            	if (eventType == XmlPullParser.TEXT) {
		            		if(tagok){
		            			for(int i=0;i<4;i++){
		            				quiz_call = xpp.getText().split(",");
		            			}
		                	}
//		            		quizs qs = new quizs(quiz_call[0],quiz_call[1],quiz_call[2],quiz_call[3],quiz_call[4],quiz_call[5],Integer.parseInt(quiz_call[6]));
//		    				
//		                	quiz_list.add(qs);
		                }
		                eventType = xpp.next();
		            }
		            runOnUiThread(new Runnable(){
			            @Override
			             public void run() {
			            	items.quiz_answer = quiz_list.get(items.quiz_no).getQuiz_answer();
			                quiz_subject_text.setText((items.quiz_no+1)+". "+quiz_list.get(items.quiz_no).getQuiz_subject().toString());
			            	quiz_content_text.setText(quiz_list.get(items.quiz_no).getQuiz_content().toString());
			             }
			        });
		            nowloding.cancel();
		        } catch (Exception e) {

		        }
			}
	    }).start();
		
        answer1.setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
				}else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
					answer1_check.setImageResource(R.drawable.check);
					answer2_check.setImageResource(0);
					answer3_check.setImageResource(0);
					answer4_check.setImageResource(0);
					items.quiz_user_selected = 1;
				}
				return false;
			}
        	
        });
        
        answer2.setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
				}else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
					answer2_check.setImageResource(R.drawable.check);
					answer1_check.setImageResource(0);
					answer3_check.setImageResource(0);
					answer4_check.setImageResource(0);
					items.quiz_user_selected = 2;
				}
				return false;
			}
        	
        });
        answer3.setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
				}else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
					answer3_check.setImageResource(R.drawable.check);
					answer1_check.setImageResource(0);
					answer2_check.setImageResource(0);
					answer4_check.setImageResource(0);
					items.quiz_user_selected = 3;					
				}
				return false;
			}
        	
        });
        answer4.setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
				}else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
					answer4_check.setImageResource(R.drawable.check);
					answer1_check.setImageResource(0);
					answer2_check.setImageResource(0);
					answer3_check.setImageResource(0);
					items.quiz_user_selected = 4;
				}
				return false;
			}
        	
        });
        
        quiz_ok_btn.setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == android.view.MotionEvent.ACTION_DOWN) {
					quiz_ok_btn.setBackgroundResource(R.drawable.quiz_ok_btn_down);
				}else if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
					quiz_ok_btn.setBackgroundResource(R.drawable.quiz_ok_btn);
					
					if(items.quiz_user_selected == 0){
						Toast.makeText(tour_quizevent.this,"문항을 선택하여 주세요",Toast.LENGTH_SHORT).show();
					}else{
						second.cancel();
						if(items.quiz_user_selected == items.quiz_answer){	
							if((items.quiz_no+1) == quiz_list.size()){//퀴즈 모든문제 풀이 완료
								Intent intent = new Intent(tour_quizevent.this, quiz_answer_ok.class);
								startActivityForResult(intent, 0);
								finish();
							}else{	//퀴즈 문제가 남았을 경우
								runOnUiThread(new Runnable(){
						            @Override
						             public void run() {
						            	Toast.makeText(tour_quizevent.this,"정답입니다! 다음문제로 이동합니다",Toast.LENGTH_SHORT).show();
						             }
						        });
								
								items.quiz_no = items.quiz_no+1;
								Intent intent = new Intent(tour_quizevent.this, tour_quizevent.class);
								startActivityForResult(intent, 0);
								finish();
							}
							
						}else{	//틀렸을 경우
							Intent intent = new Intent(tour_quizevent.this, quiz_failure.class);
							startActivityForResult(intent, 0);
							finish();
						}
					}
				}
				return false;
			}
        	
        });
    }
    
    public boolean onKeyDown( int KeyCode, KeyEvent event ){
		if( event.getAction() == KeyEvent.ACTION_DOWN ){
			second.cancel();
			items.quiz_no=0;
			if( KeyCode == KeyEvent.KEYCODE_BACK ){
				Intent intent = new Intent(tour_quizevent.this, tour_map.class);
				startActivityForResult(intent, 0);
				finish();
				
				return false;
			}
		}
		return super.onKeyDown(KeyCode, event);
	}
    
    public boolean onCreateOptionsMenu(Menu menu){
    	getMenuInflater().inflate(R.menu.quick, menu);
		return true;   	
    }

    public boolean onOptionsItemSelected(MenuItem item){
    	if(item.getItemId() == R.id.map_go){
    		startActivity(new Intent(this,tour_map.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.event_go){
    		startActivity(new Intent(this,tour_event_info.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.myinfo_go){
    		startActivity(new Intent(this,tour_myinfo.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.coupon_go){
    		startActivity(new Intent(this,tour_coupon.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.help_go){
    		startActivity(new Intent(this,tour_help.class));
    		finish();
    		return true;
    	}else if(item.getItemId() == R.id.oxquiz_go){
    		items.event_list.removeAll(items.event_list);

    		new Thread(new Runnable() {    
				@Override
				public void run() {
					runOnUiThread(new Runnable(){
						 @Override
						 public void run() {
							 AlertDialog.Builder q_level = new AlertDialog.Builder(tour_quizevent.this)
				    			.setTitle(items.appname)
				    			.setMessage("퀴즈 난이도를 선택해 주세요")
				    			.setIcon(R.drawable.icon)
				    			.setPositiveButton("초급", new DialogInterface.OnClickListener(){
				    				@Override
				    				public void onClick(DialogInterface dialog, int which) {
				    					// TODO Auto-generated method stub
				    					final ProgressDialog nowloding = ProgressDialog.show(tour_quizevent.this,"","OX 퀴즈를 불러오고 있습니다....",true);
				    			        
				    			        new Thread(new Runnable() {    
				    						@Override
				    						public void run() {				 
				    							try{
				    				    			
				    					    		URL url = null;
				    						        String resultString =null;
				    						  
				    					        	url = new URL(tour_oxquiz_call+"?app_type="+items.apptype+"&q_level="+items.q_level_easy);
				    							
				    					        	HttpURLConnection http = (HttpURLConnection)url.openConnection();  
				    					        	
				    					        	BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));  
				    					        	StringBuffer buffer = new StringBuffer();
				    								 
				    					        	int z;
				    					        	
				    								while((z=in.read()) != -1){
				    									buffer.append((char)z);
				    								}
				    								
				    								resultString= buffer.toString().trim();
				    								
				    					            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
				    					            factory.setNamespaceAware(true);
				    					            
				    					            boolean tagok = false;
				    					            
				    					            String[] quiz_call = null;
				    					            
				    					            XmlPullParser xpp = factory.newPullParser();
				    					            xpp.setInput(new StringReader(resultString));
				    					            
				    					            int eventType = xpp.getEventType();
				    					            
				    					            while (eventType != XmlPullParser.END_DOCUMENT) {
				    					                
				    					            	if(eventType == XmlPullParser.START_DOCUMENT) {
				    					                    System.out.println("Start document");
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.END_DOCUMENT) {
				    					                    System.out.println("End document");
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.START_TAG) {
				    					            		
				    					            		if(xpp.getName().equals("name")){
				    					            			tagok = true;
				    					            		}
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.END_TAG) {
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.TEXT) {
				    					            		if(tagok){
				    					            			quiz_call = xpp.getText().split(",");
				    					                	}
				    					            		quizs qs = new quizs("",quiz_call[0],"","","","","",Integer.parseInt(quiz_call[1]),0,quiz_call[2],Integer.parseInt(quiz_call[3]));
				    					            
				    					            		items.event_list.add(qs);
				    					                }
				    					                eventType = xpp.next();
				    					            }
				    					            
				    					            nowloding.cancel();
				    					            
				    					            Intent intent = new Intent(tour_quizevent.this, tour_oxquiz.class);
				    								startActivityForResult(intent, 0);
				    								finish();
				    					    		
				    							} catch (MalformedURLException e) {
				    								// TODO Auto-generated catch block
				    								e.printStackTrace();
				    							} catch (IOException e) {
				    								// TODO Auto-generated catch block								
				    								runOnUiThread(new Runnable(){
				    						            @Override
				    						             public void run() {
				    						            	AlertDialog.Builder nologin = new AlertDialog.Builder(tour_quizevent.this);
				    						    			nologin.setTitle(items.appname);
				    						    			nologin.setMessage("서버에 접속이 되지 않습니다\n네트워크를 확인 후 다시 시도해 주세요");
				    						    			nologin.setIcon(R.drawable.icon);
				    						    			nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
				    						    				@Override
				    						    				public void onClick(DialogInterface dialog, int which) {
				    						    					// TODO Auto-generated method stub
				    						    					moveTaskToBack(true);
				    						    					android.os.Process.killProcess(android.os.Process.myPid());
				    						    				}
				    						    			});
				    						    			nologin.show();
				    						             }
				    						        });
				    							}catch(Exception e){
				    								System.out.println(e.toString());
				    							}
				    						}
				    				    }).start();
				    				}
				    			})
				    			.setNeutralButton("고급", new DialogInterface.OnClickListener(){
				    				@Override
				    				public void onClick(DialogInterface dialog, int which) {
				    					// TODO Auto-generated method stub
				    					final ProgressDialog nowloding = ProgressDialog.show(tour_quizevent.this,"","OX 퀴즈를 불러오고 있습니다....",true);
				    			        
				    			        new Thread(new Runnable() {    
				    						@Override
				    						public void run() {				 
				    							try{
				    				    			
				    					    		URL url = null;
				    						        String resultString =null;
				    						  
				    					        	url = new URL(tour_oxquiz_call+"?app_type="+items.apptype+"&q_level="+items.q_level_hard);
				    							
				    					        	HttpURLConnection http = (HttpURLConnection)url.openConnection();  
				    					        	
				    					        	BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));  
				    					        	StringBuffer buffer = new StringBuffer();
				    								 
				    					        	int z;
				    					        	
				    								while((z=in.read()) != -1){
				    									buffer.append((char)z);
				    								}
				    								
				    								resultString= buffer.toString().trim();
				    								
				    					            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
				    					            factory.setNamespaceAware(true);
				    					            
				    					            boolean tagok = false;
				    					            
				    					            String[] quiz_call = null;
				    					            
				    					            XmlPullParser xpp = factory.newPullParser();
				    					            xpp.setInput(new StringReader(resultString));
				    					            
				    					            int eventType = xpp.getEventType();
				    					            
				    					            while (eventType != XmlPullParser.END_DOCUMENT) {
				    					                
				    					            	if(eventType == XmlPullParser.START_DOCUMENT) {
				    					                    System.out.println("Start document");
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.END_DOCUMENT) {
				    					                    System.out.println("End document");
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.START_TAG) {
				    					            		
				    					            		if(xpp.getName().equals("name")){
				    					            			tagok = true;
				    					            		}
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.END_TAG) {
				    					                }
				    					            	
				    					            	if (eventType == XmlPullParser.TEXT) {
				    					            		if(tagok){
				    					            			quiz_call = xpp.getText().split(",");
				    					                	}
				    					            		quizs qs = new quizs("",quiz_call[0],"","","","","",Integer.parseInt(quiz_call[1]),0,quiz_call[2],Integer.parseInt(quiz_call[3]));
				    					            
				    					            		items.event_list.add(qs);
				    					                }
				    					                eventType = xpp.next();
				    					            }
				    					            
				    					            nowloding.cancel();
				    					            
				    					            Intent intent = new Intent(tour_quizevent.this, tour_oxquiz.class);
				    								startActivityForResult(intent, 0);
				    								finish();
				    					    		
				    							} catch (MalformedURLException e) {
				    								// TODO Auto-generated catch block
				    								e.printStackTrace();
				    							} catch (IOException e) {
				    								// TODO Auto-generated catch block								
				    								runOnUiThread(new Runnable(){
				    						            @Override
				    						             public void run() {
				    						            	AlertDialog.Builder nologin = new AlertDialog.Builder(tour_quizevent.this);
				    						    			nologin.setTitle(items.appname);
				    						    			nologin.setMessage("서버에 접속이 되지 않습니다\n네트워크를 확인 후 다시 시도해 주세요");
				    						    			nologin.setIcon(R.drawable.icon);
				    						    			nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
				    						    				@Override
				    						    				public void onClick(DialogInterface dialog, int which) {
				    						    					// TODO Auto-generated method stub
				    						    					moveTaskToBack(true);
				    						    					android.os.Process.killProcess(android.os.Process.myPid());
				    						    				}
				    						    			});
				    						    			nologin.show();
				    						             }
				    						        });
				    							}catch(Exception e){
				    								System.out.println(e.toString());
				    							}
				    						}
				    				    }).start();
				    				}
				    			});
								q_level.show();
						 }
					 });
				}
		    }).start();
    	}
		return false;
    }
}
